package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.entity.Emp;
import com.itheima.pojo.entity.Empexpr;
import com.itheima.pojo.result.PageBean;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.beans.Transient;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmpMapper empMapper;

    @Override
    public PageBean page(Integer page, Integer pageSize, String name, Short gender, LocalDate begin, LocalDate end) {
        PageHelper.startPage(page, pageSize);

        List<Emp> emplist = empMapper.list(name, gender, begin, end);
        Page<Emp> p = (Page<Emp>) emplist;


        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
        return pageBean;
    }

    @Override
    public void deleteList(List<Integer> ids) {
        empMapper.deleteList(ids);
    }

    @Override
    public void save(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.insert(emp);
        Integer id = emp.getId();
        // 2. 修改员工经历
        // 2.1 拿出员工经历
        List<Empexpr> exprList = emp.getExprList();
        // 2.2 判断 员工经历是否为空
        if (ObjectUtils.isEmpty(exprList)) {
            // 为空
        } else {
            exprList.stream().forEach(ids -> ids.setEmpId(id));
            // 不为空 添加
            empMapper.addExprList(exprList);
        }
        empMapper.update(emp);
    }

    @Override
    public Emp getById(Integer id) {
        //查询员工
        Emp emp = empMapper.getById(id);
        //查询员工id查经历
        List<Empexpr> list = empMapper.getByEmpExpr(id);
        emp.setExprList(list);
        return emp;
    }

    @Transactional
    @Override
    public void update(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.update(emp);
    }


    @Override
    public void delete(Integer ids) {
        empMapper.delete(ids);

    }
}
